package com.wf.day_0617.test2;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mpk
 * @since 2024/6/17 17:17:06
 */

/*2.CyclicBarrier练习：
        模拟多线程分组计算：
        有一个随机int数组长度是1000，用5个线程分别计算200个元素的和，然后再将计算结果合并，得到最后的结果*/
//1.测试单线程计算结果
//2.测试5条线程计算结果  看结果是否一致
public class Demo {
    static int[] ints = new int[1000];

    static AtomicInteger index = new AtomicInteger(0);

    static AtomicInteger sumA = new AtomicInteger(0);

    public static void main(String[] args) {


        for (int i = 0; i < ints.length; i++) {
            ints[i] = (int) (Math.random() * 100);
        }

        int sum = 0;
        for (int anInt : ints) {
            sum += anInt;
        }
        System.out.println("单线程下1000个数字的总和" + sum);


        CyclicBarrier barrier = new CyclicBarrier(5, () -> System.out.println("多线程下1000个数字的总和:" + sumA));


        ExecutorService service = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            int threadIndex = i;
            service.submit(
                    () -> {
                        int start = threadIndex * 200;
                        int end = start + 200;
                        for (int j = start; j < end; j++) {
                            sumA.addAndGet(ints[j]);
                        }
                        try {
                            index.getAndIncrement();
                            barrier.await();
                        } catch (InterruptedException | BrokenBarrierException e) {
                            throw new RuntimeException(e);
                        }
                    });

        }

        service.shutdown();
    }

}
